import { Module } from '@nestjs/common';
import { SequelizeModule } from '@nestjs/sequelize';
import { ConfigModule } from '@nestjs/config';

import { AppController } from './app.controller';
import { AppService } from './app.service';
import { StaffModule } from './staff/staff.module';
import { StaffEntity } from '../model/entity/Staff.entity';
import { SequelizeOptions } from 'sequelize-typescript';
import * as mysql from 'mysql2/promise';
import { FrontModule } from './front/front.module';

const projectEntities = [StaffEntity];

@Module({
  imports: [
    ConfigModule.forRoot(),
    SequelizeModule.forRootAsync({
      useFactory: async () => {
        const config: Partial<SequelizeOptions> = {
          host: process.env.DB_HOST,
          port: process.env.DB_PORT ? parseInt(process.env.DB_PORT) : 3306,
          username: process.env.DB_USER,
          password: process.env.DB_PWD,
          database: process.env.DB_NAME,
        };
        const connection = await mysql.createConnection({
          host: config.host,
          port: config.port,
          user: config.username,
          password: config.password,
        });
        await connection.query(`CREATE DATABASE IF NOT EXISTS ${config.database}`);
        return {
          dialect: 'mysql',
          ...config,
          autoLoadModels: true,
          synchronize: true,
          models: [...projectEntities],
          timezone: process.env.TIMEZONE,
          logging: process.env.DB_LOG === 'true',
        };
      },
    }),
    StaffModule,
    FrontModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
